package com.shw.loco.vo;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import android.content.Context;
import android.util.Log;

import com.shw.loco.adapter.LocoDBThread;
import com.shw.loco.adapter.LocoInfoQueue;
import com.shw.loco.util.InfoUtils;
import com.shw.loco.util.MyFunc;

/**
 * @author HAHA
 */
public class ComPortInfo implements Serializable{

	private static final String TAG = "ComPortInfo";
	private String recInfo = "";
	private String recTime = "";
	private String comPort = "";
	private int portinfo;
	private byte[] portByte;
	private RFIDBoardInfo rfidBI;
	private GPSBDInfo gpsbdInfo;
	private Context context;
	private String cenToLoco;

	private int funCode = 0;// 功能码
	private int infoLength = 0;// 长度
	private int rfCount = 0;// 设备数量
	private int rf1len = 0;// 设备1ID长度
	private int rf2len = 0;// 设备2ID长度
	private String rf1ID = "";// 设备1ID
	private String rf2ID = "";// 设备2ID
	private String rfInfo = "";// 设备信息
	private String rfCourse = "";// 方向
	private String rfCal = "";// 角度、圈数、次数、
	private String rfSpeed = "";// 速度
	private String allMil = "";// 总里程
	private String rfMil = "";// 驶过rf的里程
	private String rfDate = "";// 日期时间
	private String rfCRC = "";// CRC16校验码
	private final String centerToSysMode="69000185";
	private String centerToSysErrMode="67"+InfoUtils.leftAdding(InfoUtils.TERMINALID, "0", 4)+"C500";
	private  String sysToLocoErrMode="690001C500";
	private final String sysFeedbackLoco="6900018400";
	private final String sysToRFIDErrMode="6801C300";
	private final String SysFeedbackCenter="67"+InfoUtils.leftAdding(InfoUtils.TERMINALID, "0", 4)+"8500";
	private final String SysToCenterMode="67"+InfoUtils.leftAdding(InfoUtils.TERMINALID, "0", 4)+"04";

	public ComPortInfo(String comPort, byte[] buffer, int size, int portinfo) throws Exception{
		this.comPort = comPort;
		this.portinfo = portinfo;
		byte[] rec = new byte[size];
		for (int i = 0; i < size; i++) {
			rec[i] = buffer[i];
		}
		this.portByte = rec;
		if (portinfo == InfoUtils.PORT232_GPS) {
			recInfo = new String(portByte);
			/*if(!recInfo.startsWith("$GPRMC")){
				recInfo="1";
			}*/
			recInfo=recInfo.substring(recInfo.indexOf("$GPRMC"),recInfo.length());
		} else {
			recInfo = MyFunc.ByteArrToHex(portByte);
		}
		if(false){LocoInfoQueue.sourceInfo.add(recInfo);}
		Log.d(TAG, "@@@@@@@@@   " + recInfo);
		unpack(recInfo);
		SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
		recTime = dateFormat.format(new java.util.Date());

	}

	public ComPortInfo(String comPort, byte[] buffer, int size, int portinfo,
			Context context) throws Exception{
		this.comPort = comPort;
		this.context = context;
		this.portinfo = portinfo;
		byte[] rec = new byte[size];
		for (int i = 0; i < size; i++) {
			rec[i] = buffer[i];
		}
		this.portByte = rec;
		if (portinfo == InfoUtils.PORT232_GPS) {
			recInfo = new String(portByte);
			/*if(!recInfo.startsWith("$GPRMC")){
				recInfo="1";
			}*/
			recInfo=recInfo.substring(recInfo.indexOf("$GPRMC"),recInfo.length());
		} else {
			recInfo = MyFunc.ByteArrToHex(portByte);
		}
		if(false){LocoInfoQueue.sourceInfo.add(recInfo);}
		Log.d(TAG, "@@@@@@@@@   " + recInfo);
		unpack(recInfo);
		SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
		recTime = dateFormat.format(new java.util.Date());
		this.portinfo = portinfo;

	}

	public ComPortInfo(String comPort, String info, int portinfo) throws Exception{
		this.comPort = comPort;
		this.context = context;
		this.portinfo = portinfo;
		recInfo=info;
		if(false){LocoInfoQueue.sourceInfo.add(recInfo);}
		Log.d(TAG, "@@@@@@@@@   " + recInfo);
		unpack(recInfo);
		SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
		recTime = dateFormat.format(new java.util.Date());
		this.portinfo = portinfo;

	}
	public String getRecInfo() {
		return recInfo;
	}

	public void setRecInfo(String recInfo) {
		this.recInfo = recInfo;
	}

	public String getRecTime() {
		return recTime;
	}

	public void setRecTime(String recTime) {
		this.recTime = recTime;
	}

	public String getComPort() {
		return comPort;
	}

	public void setComPort(String comPort) {
		this.comPort = comPort;
	}

	public byte[] getPortByte() {
		return portByte;
	}

	public void setPortByte(byte[] portByte) {
		this.portByte = portByte;
	}

	public int getPortinfo() {
		return portinfo;
	}

	public void setPortinfo(int portinfo) {
		this.portinfo = portinfo;
	}

	private void unpack(String recInfo) throws Exception{
		switch (portinfo) {
		case 0:
			if (recInfo.startsWith(InfoUtils.RFID_REQ_HEAD)) {
				rfidBI = new RFIDBoardInfo();
				String str = recInfo.substring(2 * 2);
				unpack_RFID(str);
			}
			break;
		case 1:
//			if (recInfo.startsWith("$GPRMC") || recInfo.startsWith("$BDRMC")|| recInfo.startsWith("$GPGGA")) {
			if (recInfo.startsWith("$GPRMC")) {
				gpsbdInfo = new GPSBDInfo();
				unpack_GPSBD(recInfo);
			}
			break;
		case 2:
			if (recInfo.startsWith("69")) {
				if(!InfoUtils.checkCRC16(recInfo)){
					String str = recInfo.substring(6,8).toUpperCase();
					if(str.equals("03")){
						sysToLocoErrMode="690001C300";
					}else if(str.equals("04")){
						sysToLocoErrMode="690001C400";
					}
					LocoInfoQueue.locoErrorQueVecotr.add(InfoUtils.HexToByteArr(sysToLocoErrMode+InfoUtils.CRC_16(InfoUtils.HexToByteArr(sysToLocoErrMode))));
					LocoInfoQueue.locoErrorQue.add("Q");
					return;
				}
				String str = recInfo.substring(3 * 2);
				unpack_Host(recInfo);
			}else{
				LocoInfoQueue.locoErrorQueVecotr.add(InfoUtils.HexToByteArr(sysToLocoErrMode+InfoUtils.CRC_16(InfoUtils.HexToByteArr(sysToLocoErrMode))));
				LocoInfoQueue.locoErrorQue.add("Q");
				return;
			}
			break; 
		case 3: 
			if (recInfo.startsWith("67")) {
				 String str = recInfo.substring(6,8).toUpperCase();
				if(!InfoUtils.checkCRC16(recInfo)){
					if(str.equals("06")){
						centerToSysErrMode="67"+InfoUtils.leftAdding(InfoUtils.TERMINALID, "0", 4)+"C600";
					}else if(str.equals("07")){
						centerToSysErrMode="67"+InfoUtils.leftAdding(InfoUtils.TERMINALID, "0", 4)+"C700";
					}
					LocoInfoQueue.resultToCenterVector.add(InfoUtils.HexToByteArr(centerToSysErrMode+InfoUtils.CRC_16(InfoUtils.HexToByteArr(centerToSysErrMode))));
					return;
				}
				unpack_3G(recInfo);
			}else{
				LocoInfoQueue.resultToCenterVector.add(InfoUtils.HexToByteArr(centerToSysErrMode+InfoUtils.CRC_16(InfoUtils.HexToByteArr(centerToSysErrMode))));
				return;
			}
			break;
		default:
			break;
		}
	}

	private void unpack_3G(String recInfo) throws Exception{
		String str = recInfo;
		str = str.substring(3 * 2);
		funCode = Integer.parseInt(str.substring(0, 1 * 2), 16);
		str = str.substring(1 * 2);
		switch (funCode) {
		case 138:// 8a

			break;
		case 202:// ca

			break;
		case 132:// 84  调度中心回馈收到主控板转发机车的数据
			LocoInfoQueue.centerToLocoList.add(InfoUtils.HexToByteArr(sysFeedbackLoco+InfoUtils.CRC_16(InfoUtils.HexToByteArr(sysFeedbackLoco))));
			LocoInfoQueue.locoQueVecotr.add("Q");
			break;
		case 5:// 05 调度中心发给给机车的数据
			String centerToSys=centerToSysMode+recInfo.substring(8, recInfo.length()-4);
			LocoInfoQueue.centerToLocoList.add(InfoUtils.HexToByteArr(centerToSys+InfoUtils.CRC_16(InfoUtils.HexToByteArr(centerToSys))));
			LocoInfoQueue.resultToCenterVector.add(InfoUtils.HexToByteArr(SysFeedbackCenter+InfoUtils.CRC_16(InfoUtils.HexToByteArr(SysFeedbackCenter))));
			this.cenToLoco = recInfo;
			break;
		case 6:// 06 调度中心下发区间表的数据
			new LocoDBThread(LocoDBThread.DB_ADD, 2, context, recInfo, false).start();
			break;
		case 7:// 07 调度中心下发RFID表的数据
			new LocoDBThread(LocoDBThread.DB_ADD, 0, context, recInfo, false).start();
			break;

		default:
			break;
		}
	}

	private void unpack_Host(String recInfo)throws Exception{
		String str = recInfo;
		str = str.substring(3 * 2);
		funCode = Integer.parseInt(str.substring(0, 1 * 2), 16);
		str = str.substring(1 * 2);
		switch (funCode) {
		case 3:// 请求RFID数据
			LocoInfoQueue.locoRFIDQueVecotr.add("Q");
			break;
		case 4:// loco向中心转发的数据
			String sysToCenter=SysToCenterMode+recInfo.substring(8, recInfo.length()-4);
			LocoInfoQueue.resultToCenterVector.add(InfoUtils.HexToByteArr(sysToCenter+InfoUtils.CRC_16(InfoUtils.HexToByteArr(sysToCenter))));
			
			break;
		case 5:// 请求中心转发数据
			LocoInfoQueue.locoQueVecotr.add("Q");
			break;
		default:
			break;
		}
	}

	private void unpack_GPSBD(String recInfo) {
		try{
		String[] rec = recInfo.split(",");
		gpsbdInfo.setGbMode(rec[0]);
		gpsbdInfo.setGbTime(rec[1]);
		gpsbdInfo.setGbState(rec[2]);
		String latstr=rec[3].replace(".", "");
		//转google维度
//		gpsbdInfo.setGbLat(InfoUtils.LatTolat(latstr.substring(0, 2)+"."+latstr.substring(2)));
		gpsbdInfo.setGbLat(latstr.substring(0, 2)+"."+latstr.substring(2));
		gpsbdInfo.setGbLatStatus(rec[4]);
		String lonstr=rec[5].replace(".", "");
		//转Google经度
//		gpsbdInfo.setGbLon(InfoUtils.LonTolon(lonstr.substring(0, 3)+"."+lonstr.substring(3)));
		gpsbdInfo.setGbLon(lonstr.substring(0, 3)+"."+lonstr.substring(3));
		gpsbdInfo.setGbLonStatus(rec[6]);
		gpsbdInfo.setGbSpeed(rec[7]);
		gpsbdInfo.setGbCourse(rec[8]);
		gpsbdInfo.setGbDate(rec[9]);
		gpsbdInfo.setGbDeclination(rec[10]);
		gpsbdInfo.setGbDecCourse(rec[11]);
		gpsbdInfo.setGbCheck(rec[12]);
		LocoInfoQueue.gpsbdVector.clear();
		LocoInfoQueue.gpsbdVector.add(gpsbdInfo);}catch(Exception e){Log.d("ComPortInfo", "error");}
	}

	private void unpack_RFID(String recInfo){
		try{
		String str = recInfo;
		funCode = Integer.parseInt(str.substring(0, 1 * 2), 16);
		str = str.substring(1 * 2);
		switch (funCode) {
		case 129:// 81下写时钟指令正确回馈
			/*if (str.startsWith("00"))
				if (context != null) {
					Looper.prepare();
					Toast.makeText(context, "下发时钟正确", Toast.LENGTH_SHORT)
							.show();
					Looper.loop();
				}*/
			break;
		case 193:// c1下写时钟指令错误回馈
			/*if (str.startsWith("00"))
				if (context != null) {
					Looper.prepare();
					Toast.makeText(context, "下发时钟错误", Toast.LENGTH_SHORT)
							.show();
					Looper.loop();
				}*/
			break;
		case 130:// 82读取当前时钟正确回馈

			break;
		case 194:// c2读取当前时钟错误回馈
			/*if (str.startsWith("00"))
				if (context != null) {
					Looper.prepare();
					Toast.makeText(context, "读取时钟错误", Toast.LENGTH_SHORT)
							.show();
					Looper.loop();
				}*/
			break;
		case 131:// 83采集数据正确回馈
			infoLength = Integer.parseInt(str.substring(0, 1 * 2), 16);
			rfidBI.setInfoLength(infoLength);
			Log.d(TAG, "rfidBI  " + rfidBI);
			str = str.substring(1 * 2);
			rfCount = Integer.parseInt(str.substring(0, 1 * 2), 16);
			rfidBI.setRfCount(rfCount);
			Log.d(TAG, "rfCount  " + rfCount);
			str = str.substring(1 * 2);
			rfInfo = str.substring(0, 30 * 2);
			rfidBI.setRfInfo(recInfo);
			Log.d(TAG, "rfInfo  " + rfInfo);
			str = str.substring(30 * 2);
			rf1len = Integer.parseInt(rfInfo.substring(0, 1 * 2), 16);
			rfidBI.setRf1len(rf1len);
			Log.d(TAG, "rf1len  " + rf1len);
			rfInfo = rfInfo.substring(1 * 2);
			Log.d(TAG, "rfidBI  " + rfidBI);
			rf1ID = rfInfo.substring(0, rf1len * 2);
			rfidBI.setRf1ID(rf1ID);
			Log.d(TAG, "rf1ID  " + rf1ID);
			rfInfo = rfInfo.substring(rf1len * 2);
			if (rfCount == 2) {
				rf2len = Integer.parseInt(rfInfo.substring(0, 1 * 2), 16);
				rfidBI.setRf2len(rf2len);
				Log.d(TAG, "rf2len  " + rf2len);
				rfInfo = rfInfo.substring(1 * 2);
				rf2ID = rfInfo.substring(0, rf1len * 2);
				rfidBI.setRf2ID(rf2ID);
				Log.d(TAG, "rf2ID  " + rf2ID);
				rfInfo = rfInfo.substring(rf1len * 2);
			}
			rfCourse = str.substring(0, 1 * 2);
			rfidBI.setRfCourse(rfCourse);
			Log.d(TAG, "rfCourse  " + rfCourse);
			str = str.substring(1 * 2);
			rfCal = str.substring(0, 10 * 2);
			rfidBI.setRfCal(rfCal);
			Log.d(TAG, "rfCal  " + rfCal);
			str = str.substring(10 * 2);
			rfSpeed = str.substring(0, 2 * 2);
			rfidBI.setRfSpeed(rfSpeed);
			Log.d(TAG, "rfSpeed  " + rfSpeed);
			str = str.substring(2 * 2);
			allMil = str.substring(0, 4 * 2);
			rfidBI.setAllMil(new BigDecimal(InfoUtils.byte2int_Float(InfoUtils.HexToByteArr(allMil))).setScale(2,BigDecimal.ROUND_DOWN).toString());
			Log.d(TAG, "allMil  " + allMil);
			str = str.substring(4 * 2);
			rfMil = str.substring(0, 4 * 2);
			rfidBI.setRfMil0x(rfMil);
			rfidBI.setRfMil(new BigDecimal(InfoUtils.byte2int_Float(InfoUtils.HexToByteArr(rfMil))).setScale(2,BigDecimal.ROUND_DOWN).toString());
			Log.d(TAG, "rfMil  " + rfMil);
			str = str.substring(4 * 2);
			rfDate = InfoUtils.hexToDateStr(str.substring(0, 7 * 2));
			rfidBI.setRfDate0x(str.substring(0, 7 * 2));
			rfidBI.setRfDate(rfDate);
			Log.d(TAG, "rfDate  " + rfDate);
			str = str.substring(7 * 2);
			rfCRC = str.substring(0, 2 * 2);
			rfidBI.setRfCRC(rfCRC);
			Log.d(TAG, "rfCRC  " + rfCRC);
			if(LocoInfoQueue.gpsbdVector.size()>0)
			rfidBI.setGpsbdInfo(LocoInfoQueue.gpsbdVector.get(0));
			
			LocoInfoQueue.addRFIDV(rfidBI);
			break;
		case 195:// c3采集数据错误回馈

			break;
		case 132:// 84下写参数正确回馈
			/*if (str.startsWith("00"))
				if (context != null) {
					Looper.prepare();
					Toast.makeText(context, "下写参数正确", Toast.LENGTH_SHORT)
							.show();
					Looper.loop();
				}*/
			break;
		case 196:// c4下写参数错误回馈
			/*if (str.startsWith("00"))
				if (context != null) {
					Looper.prepare();
					Toast.makeText(context, "下写参数错误", Toast.LENGTH_SHORT)
							.show();
					Looper.loop();
				}*/
			break;
		case 133:// 85读取参数正确回馈

			break;
		case 197:// c5读取参数错误回馈
			/*if (str.startsWith("00"))
				if (context != null) {
					Looper.prepare();
					Toast.makeText(context, "读取参数错误", Toast.LENGTH_SHORT)
							.show();
					Looper.loop();
				}*/
			break;
		default:
			break;
		}
		}catch(Exception e){Log.d("ComPortInfo", "error");}
	}

	public static void main(String[] args) throws Exception{
		ComPortInfo cpi = new ComPortInfo("", null, 1, 0);
		cpi.unpack("6801833B020CBBBBBBBBBBBBBBBBBBBB10210CBBBBBBBBBBBBBBBBBBBB10140000000000B3001B000000070000003D00251EB34208D87E413331210003111304BB");
		RFIDBoardInfo rfidBI=new RFIDBoardInfo();
		rfidBI.setInfoLength(1);
		rfidBI.setRfCount(1);
		rfidBI.setRfInfo("");
		rfidBI.setRf1len(12);
		rfidBI.setRf1ID("010203040506");
		rfidBI.setRfCourse("00");
		rfidBI.setRfCal("");
		rfidBI.setRfSpeed("100");
		rfidBI.setAllMil("900");	
		rfidBI.setRfMil("0.5");
		rfidBI.setRfDate0x(InfoUtils.dateToHexStr());
		rfidBI.setRfDate(InfoUtils.hexToDateStr(InfoUtils.dateToHexStr()));
		rfidBI.setRfCRC("0000");
	}

}